<?php defined('SYSPATH') or die('No direct script access.');

class Model_Composition extends Model_Filter
{  
    const COTTON_COMPOSITION                = 1;
    const POLYESTER_COMPOSITION             = 2;
    const SPANDEX_COMPOSITION               = 3;
    const LEATHER_COMPOSITION               = 4;
    const RAYON_COMPOSITION                 = 5;
    
    const POLYAMIDE_COMPOSITION             = 6;  
    const NYLON_COMPOSITION                 = 7;
    const PLASTIC_COMPOSITION               = 8;
    const FAKE_LEATHER_COMPOSITION          = 9;
    const WOOL_COMPOSITION                  = 10;
    
    const TEXTILE_COMPOSITION               = 11;
    const ACRYLIC_COMPOSITION               = 12;
    const METAL_COMPOSITION                 = 13;
    const LYCRA_COMPOSITION                 = 14;
    const COUNTY_COMPOSITION                = 15;
    
    const POLYURETHANE_COMPOSITION          = 16;
    const SILK_COMPOSITION                  = 17;
    const SYNTHETIC_MATERIAL_COMPOSITION    = 18;
    const NATURAL_VELOR_COMPOSITION         = 19;
    const SUEDE_COMPOSITION                 = 20;
    
    const VELOR_COMPOSITION                 = 21; 
    const RHINESTONE_COMPOSITION            = 22; 
    const NATURAL_SUEDE_COMPOSITION         = 23; 
    const CARDBOARD_COMPOSITION             = 24; 
    const PVC_COMPOSITION                   = 25; 
    
    const MODAL_COMPOSITION                 = 26;
    const FAKE_FUR_COMPOSITION              = 27;
    const POLYACRYL_COMPOSITION             = 28;
    const PORCELAIN_COMPOSITION             = 29;
    const NATURAL_NUBUCK_COMPOSITION        = 30;
    
    const GLASS_COMPOSITION                 = 31;
    const FAUX_COMPOSITION                  = 32;
    const ANGORA_COMPOSITION                = 33;
    const CASHMERE_COMPOSITION              = 34;
    const RUBBER_COMPOSITION                = 35;
    
    const STEEL_COMPOSITION                 = 36;
    const PAPER_COMPOSITION                 = 37;
    const NUBUCK_COMPOSITION                = 38;
    const SPLITS_COMPOSITION                = 39;
    const STAINLESS_STEEL_COMPOSITION       = 40;
    
    const FAKE_SUEDE_COMPOSITION            = 41; 
    const FAKE_MATERIAL_COMPOSITION         = 42; 
    const FAKE_NUBUCK_COMPOSITION           = 43; 
    const WOOD_COMPOSITION                  = 44; 
    const TENCEL_COMPOSITION                = 45; 
    const CROSSLITE_COMPOSITION             = 46; 

    
    public static $compositions = array(
        'hlopok'                    => self::COTTON_COMPOSITION,
        'poliester'                 => self::POLYESTER_COMPOSITION,
        'elastan'                   => self::SPANDEX_COMPOSITION,
        'koja'                      => self::LEATHER_COMPOSITION,
        'viskoza'                   => self::RAYON_COMPOSITION,
        
        'poliamid'                  => self::POLYAMIDE_COMPOSITION,       
        'neylon'                    => self::NYLON_COMPOSITION,
        'plastik'                   => self::PLASTIC_COMPOSITION,
        'iskusstvennaya-koja'       => self::FAKE_LEATHER_COMPOSITION,
        'sherst'                    => self::WOOL_COMPOSITION,
        
        'tekstil'                   => self::TEXTILE_COMPOSITION,
        'akril'                     => self::ACRYLIC_COMPOSITION,
        'metall'                    => self::METAL_COMPOSITION,
        'laykra'                    => self::LYCRA_COMPOSITION,
        'len'                       => self::COUNTY_COMPOSITION,
 
        'poliuretan'                => self::POLYURETHANE_COMPOSITION,
        'shelk'                     => self::SILK_COMPOSITION,
        'sinteticheskiy-material'   => self::SYNTHETIC_MATERIAL_COMPOSITION,
        'naturalnyiy-velyur'        => self::NATURAL_VELOR_COMPOSITION,
        'zamsha'                    => self::SUEDE_COMPOSITION,
        
        'velyur'                    => self::VELOR_COMPOSITION,
        'strazyi'                   => self::RHINESTONE_COMPOSITION,
        'naturalnaya-zamsha'        => self::NATURAL_SUEDE_COMPOSITION,
        'karton'                    => self::CARDBOARD_COMPOSITION,
        'pvh'                       => self::PVC_COMPOSITION,
        
        'modal'                     => self::MODAL_COMPOSITION,
        'iskusstvennyiy-meh'        => self::FAKE_FUR_COMPOSITION,
        'poliakril'                 => self::POLYACRYL_COMPOSITION,
        'farfor'                    => self::PORCELAIN_COMPOSITION,
        'naturalnyiy-nubuk'         => self::NATURAL_NUBUCK_COMPOSITION,
        
        'steklo'                    => self::GLASS_COMPOSITION,
        'ekokoja'                   => self::FAUX_COMPOSITION,
        'angora'                    => self::ANGORA_COMPOSITION,
        'kashemir'                  => self::CASHMERE_COMPOSITION,
        'rezina'                    => self::RUBBER_COMPOSITION,
        
        'stal'                      => self::STEEL_COMPOSITION,
        'bumaga'                    => self::PAPER_COMPOSITION,
        'nubuk'                     => self::NUBUCK_COMPOSITION,
        'spilok'                    => self::SPLITS_COMPOSITION,
        'nerjaveyuschaya-stal'      => self::STAINLESS_STEEL_COMPOSITION,
        
        'iskusstvennaya-zamsha'     => self::FAKE_SUEDE_COMPOSITION,
        'iskusstvennyiy-material'   => self::FAKE_MATERIAL_COMPOSITION,
        'iskusstvennyiy-nubuk'      => self::FAKE_NUBUCK_COMPOSITION,
        'derevo'                    => self::WOOD_COMPOSITION,
        'tensel'                    => self::TENCEL_COMPOSITION,
        'croslite'                  => self::CROSSLITE_COMPOSITION,
    );
    
    public static $composition_options = array(       
        self::COTTON_COMPOSITION => array(
            'name'        => 'хлопок',
            'single_form' => 'из хлопока',
            'plural_form' => 'хлопковые',
            'genitive_form' => 'хлопковых',  
        ),
        self::POLYESTER_COMPOSITION => array(
            'name'        => 'полиэстер',
            'single_form' => 'из полиэстера',
            'plural_form' => 'полиэстеровые',
            'genitive_form' => 'полиэстеровых',
        ),
        self::SPANDEX_COMPOSITION => array(
            'name'        => 'эластан',
            'single_form' => 'из эластана',
            'plural_form' => 'эластановые',
            'genitive_form' => 'эластановых',
        ),
        self::LEATHER_COMPOSITION => array(
            'name'        => 'натуральная кожа',
            'single_form' => 'из натуральной кожи',
            'plural_form' => 'кожаные',
            'genitive_form' => 'кожаных',
        ),
        self::RAYON_COMPOSITION => array(
            'name'        => 'вискоза',
            'single_form' => 'из вискозы',
        ),
        
        self::POLYAMIDE_COMPOSITION => array(
            'name'        => 'полиамид',
            'single_form' => 'из полиамида',
        ),    
        self::NYLON_COMPOSITION => array(
            'name'        => 'нейлон',
            'single_form' => 'из нейлона',
            'plural_form' => 'нейлоновые',
            'genitive_form' => 'нейлоновых',
        ),
        self::PLASTIC_COMPOSITION => array(
            'name'        => 'пластик',
            'single_form' => 'из пластика',
            'plural_form' => 'пластиковые',
            'genitive_form' => 'пластиковых',
        ),
        self::FAKE_LEATHER_COMPOSITION => array(
            'name'        => 'искусственная кожа',
            'single_form' => 'из искусственной кожи',
        ),
        self::WOOL_COMPOSITION => array(
            'name' => 'шерсть',
            'single_form' => 'из шерсти',
            'plural_form' => 'шерстяные',
            'genitive_form' => 'шерстяных',
        ),
        
        self::TEXTILE_COMPOSITION => array(
            'name'        => 'текстиль',
            'single_form' => 'из текстиля',
            'plural_form' => 'текстильные',
            'genitive_form' => 'текстильных',
        ),
        self::ACRYLIC_COMPOSITION => array(
            'name'        => 'акрил',
            'single_form' => 'из акрила',
            'plural_form' => 'акриловые',
            'genitive_form' => 'акриловых',
        ),
        self::METAL_COMPOSITION => array(
            'name'        => 'металл',
            'single_form' => 'из металла',
            'plural_form' => 'металлические',
            'genitive_form' => 'металлических',
        ),
        self::LYCRA_COMPOSITION => array(
            'name'        => 'лайкра',
            'single_form' => 'из лайкры',
            'plural_form' => 'лайкровые',
            'genitive_form' => 'лайкровых',
        ),
        self::COUNTY_COMPOSITION => array(
            'name'        => 'лен',
            'single_form' => 'из льна',
            'plural_form' => 'льняные',
            'genitive_form' => 'льняных',
        ),
        
        self::POLYURETHANE_COMPOSITION => array(
            'name'        => 'полиуретан',
            'single_form' => 'из полиуретана',
            'plural_form' => 'полиуретановые',
            'genitive_form' => 'полиуретановых',
        ),
        self::SILK_COMPOSITION => array(
            'name'        => 'шелк',
            'single_form' => 'из шелка',
            'plural_form' => 'шелковые',
            'genitive_form' => 'шелковых',
        ),
        self::SYNTHETIC_MATERIAL_COMPOSITION => array(
            'name'        => 'синтетический материал',
            'single_form' => 'из синтетического материала',
        ),
        self::NATURAL_VELOR_COMPOSITION => array(
            'name'        => 'натуральный велюр',
            'single_form' => 'из натурального велюра',
            'plural_form' => 'велюровые',
            'genitive_form' => 'велюровых',
        ),
        self::NATURAL_SUEDE_COMPOSITION => array(
            'name'        => 'натуральная замша',
            'single_form' => 'из натуральной замши',
        ),
        self::SUEDE_COMPOSITION => array(
            'name'        => 'замша',
            'single_form' => 'из замши',
            'plural_form' => 'замшевые',
            'genitive_form' => 'замшевых',
        ),
        
        self::VELOR_COMPOSITION => array(
            'name'        => 'велюр',
            'single_form' => 'из велюра',
            'plural_form' => 'велюровые',
            'genitive_form' => 'велюровых',
        ),
        self::RHINESTONE_COMPOSITION => array(
            'name'        => 'стразы',
            'single_form' => 'со стразами',
        ),
        self::CARDBOARD_COMPOSITION => array(
            'name'        => 'картон',
            'single_form' => 'из картона',
        ),
        self::PVC_COMPOSITION => array(
            'name'        => 'ПВХ',
            'single_form' => 'из ПВХ',
        ),
        
        self::MODAL_COMPOSITION => array(
            'name'        => 'модал',
            'single_form' => 'из модала',
        ),
        self::FAKE_FUR_COMPOSITION => array(
            'name'        => 'искусственный мех',
            'single_form' => 'из искусственного меха',
        ),
        self::POLYACRYL_COMPOSITION => array(
            'name'        => 'полиакрил',
            'single_form' => 'из полиакрила',
            'plural_form' => 'полиакриловые',
            'genitive_form' => 'полиакриловых',
        ),
        self::PORCELAIN_COMPOSITION => array(
            'name'        => 'фарфор',
            'single_form' => 'из фарфора',
            'plural_form' => 'фарфоровые',
            'genitive_form' => 'фарфоровых',
        ),
        self::NATURAL_NUBUCK_COMPOSITION => array(
            'name'        => 'натуральный нубук',
            'single_form' => 'из натурального нубука',
            'plural_form' => 'нубуковые',
            'genitive_form' => 'нубуковых',
        ),
        
        self::GLASS_COMPOSITION => array(
            'name'        => 'стекло',
            'single_form' => 'из стекла',
            'plural_form' => 'стекляные',
            'genitive_form' => 'стекляных',
        ),
        self::FAUX_COMPOSITION => array(
            'name'        => 'экокожа',
            'single_form' => 'из экокожи',
        ),
        self::ANGORA_COMPOSITION => array(
            'name'        => 'ангора',
            'single_form' => 'из ангоры',
            'plural_form' => 'ангоровые',
            'genitive_form' => 'ангоровых',
        ),
        self::CASHMERE_COMPOSITION => array(
            'name'        => 'кашемир',
            'single_form' => 'из кашемира',
            'plural_form' => 'кашемировые',
            'genitive_form' => 'кашемировых',
        ),
        self::RUBBER_COMPOSITION => array(
            'name'        => 'резина',
            'single_form' => 'из резины',
            'plural_form' => 'резиновые',
            'genitive_form' => 'резиновых',
        ),
        
        self::STEEL_COMPOSITION => array(
            'name'        => 'сталь',
            'single_form' => 'из стали',
            'plural_form' => 'стальные',
            'genitive_form' => 'стальных',
        ),
        self::PAPER_COMPOSITION => array(
            'name'        => 'бумага',
            'single_form' => 'из бумаги',
            'plural_form' => 'бумажные',
            'genitive_form' => 'бумажных',
        ),
        self::NUBUCK_COMPOSITION => array(
            'name'        => 'нубук',
            'single_form' => 'из нубука',
            'plural_form' => 'нубуковые',
            'genitive_form' => 'нубуковых',
        ),
        self::SPLITS_COMPOSITION => array(
            'name'        => 'спилок',
            'single_form' => 'из спилка',
            'plural_form' => 'спилковые', 
            'genitive_form' => 'спилковых', 
        ),
        self::STAINLESS_STEEL_COMPOSITION => array(
            'name'        => 'нержавеющая сталь',
            'single_form' => 'из нержавеющей стали',
        ),
        
        self::FAKE_SUEDE_COMPOSITION => array(
            'name'        => 'искусственная замша',
            'single_form' => 'из искусственной замши',
        ),
        self::FAKE_MATERIAL_COMPOSITION => array(
            'name'        => 'искусственный материал',
            'single_form' => 'из искусственного материаал', 
        ),
        self::FAKE_NUBUCK_COMPOSITION => array(
            'name'        => 'искусственный нубук',
            'single_form' => 'из искусственного нубука',
        ),
        self::WOOD_COMPOSITION => array(
            'name'        => 'дерево',
            'single_form' => 'из дерева',
            'plural_form' => 'деревянные',
            'genitive_form' => 'деревянных',
        ),
        self::TENCEL_COMPOSITION => array(
            'name'        => 'тенсел',
            'single_form' => 'из тенсела',
        ),
        self::CROSSLITE_COMPOSITION => array(
            'name'        => 'croslite',
            'single_form' => 'croslite',
        ),
    );
    
    public static function get_compositions($category = null, $brand = null, $color = null, $composition = null, $season = null, $shop = null, $price = null, $use_denormalization = true, $disable_cache = false)
    {
        $ids = array();
        $category_id = self::_get_category_id($category, $ids);
        
        $brand_id    = self::_get_brand_id($brand);
        
        $color_id    = self::_get_color_id($color);
        
        $composition_id = self::_get_composition_id($composition);
        
        $season_id   = self::_get_season_id($season);
        
        $shop_id     = self::_get_shop_id($shop);
        
        $from_price  = self::_get_from_price($price);
        $to_price    = self::_get_to_price($price);
        
        if (!$disable_cache && $compositions = Cache::instance()->get('catalog_compositions_'.$category_id.'_'.$brand_id.'_'.$color_id.'_'.$season_id.'_'.$shop_id.'_'.$from_price.'_'.$to_price)) {
            return $compositions;
        }
        
        $isset_denormalized_data = null;
        $use_denormalization     = false; 
        if ($use_denormalization) {
            // Узнаем, используется ли денормализация
            $isset_denormalized_data = self::_isset_denormalized_data($category_id, $brand_id, $color_id, $composition_id, $season_id, $shop_id, $price);   
        }
        
        $stat = DB::select('composition_id', array(DB::expr('COUNT( * )'), 'count'))
                    ->from('products')
                    ->where('is_available', '=', 1)
                    ->where('composition_id', '!=', 0);
                    
        if (is_array($ids) && count($ids) > 0) {
            $stat->where('category_id', 'IN', $ids);
        }
                    
        if ($brand_id) {
            $stat->where('brand_id', '=', $brand_id); 
        }   
             
        if ($color_id) {
            $stat->where('color_id', '=', $color_id);   
        }
        
        if ($season_id) {
            $stat->where('season_id', '=', $season_id);   
        }
        
        if ($shop_id) {
            $stat->where('shop_id', '=', $shop_id);    
        }
        
        if ($from_price) {
            $stat->where('price', '>=', $from_price);    
        }
        if ($to_price) {
            $stat->where('price', '<=', $to_price); 
        }
        
        if ($use_denormalization && $isset_denormalized_data) {
            $stat = self::_get_denormalized_data('composition_id', $category_id, $brand_id, $color_id, null, $season_id, $shop_id, $price);    
        } else {             
            $stat = $stat
                    ->group_by('composition_id')
                    ->order_by('count', 'DESC')
                    ->limit(15)
                    ->execute()
                    ->as_array();
        }
        
        $compositions = array();
        $all_compositions = self::get_all_compositions();
        foreach ($stat as $composition) {
            $compositions[$composition['composition_id']] = $all_compositions[$composition['composition_id']];
            $compositions[$composition['composition_id']]['count'] = $composition['count'];            
        } 
        usort($compositions, array(__CLASS__, '_compare'));
        
        Cache::instance()->set('catalog_compositions_'.$category_id.'_'.$brand_id.'_'.$color_id.'_'.$season_id.'_'.$shop_id.'_'.$from_price.'_'.$to_price, $compositions);
        return $compositions;    
    }
    
    public static function get_all_compositions()
    {
        $compositions = array();
        foreach (self::$compositions as $url => $value) {
            $compositions[$value] = self::$composition_options[$value];
            $compositions[$value]['url'] = $url;
            $compositions[$value]['id']  = $value;        
        } 
        return $compositions;   
    }
    
    public static function get_composition_by_url($url)
    {
        $compositions = self::get_all_compositions();
        foreach ($compositions as $composition) {
            if ($composition['url'] == $url) {
                return $composition;    
            }    
        }
        return null;
    }
}
